/*
 * Creado el 07/06/2006
 *
 * TODO Para cambiar la plantilla de este archivo generado, vaya a
 * Ventana - Preferencias - Java - Estilo de codigo - Plantillas de codigo
 */
package guru.util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author sventura
 *
 * TODO Para cambiar la plantilla de este comentario generado, vaya a
 * Ventana - Preferencias - Java - Estilo de codigo - Plantillas de codigo
 */
/**
 * @author Santiago Ventura
 *  
 */
public class Mail{

    private MimeMessage message;
    private String from;
    private String subject;
    private String messageContent;
    private String messageID;

    protected Hashtable toAddresses = new Hashtable();
    protected Hashtable ccAddresses = new Hashtable();
    protected Hashtable bccAddresses = new Hashtable();
    protected Hashtable replyToAddresses = new Hashtable();
    private String fromName;


    /**
     * Constructor de la clase Mail que recibe un objeto del tipo javax.mail.Message del API JavaMail.
     * Es util cuando se trata de objetos Message recuperador a traves de los protocolos POP3 o IMAP.
     * @param msg
     */
    public Mail(Message msg) {
        //Messages's data.
        try {
            this.message = (MimeMessage) msg;
        } catch (Exception e) {
            e.printStackTrace();
        }

        //get
        try {
            InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];
            from = fromAddress.getAddress();
        } catch (Exception e) {
            from = null;
        }
        //get subject.
        try {
            subject = message.getSubject();
        } catch (Exception e) {
            subject = null;
        }
        //get message content.
        try {
            messageContent = (String) message.getContent();
        } catch (Exception e) {
            messageContent = null;
        }
        try {
            messageID = message.getMessageID();
        } catch (Exception e) {
            messageContent = null;
        }
    }

    /**
     * Constructor de la clase Mail. Puede ser muy util para construir objetos javax.mail.Message que se desean enviar
     * a traves del protocolo SMTP.
     * @param fromName
     * @param fromAddress
     * @param subject
     */
    public Mail(String fromName, String fromAddress, String subject) {
        this.fromName = fromName;
        this.from = fromAddress;
        this.subject = subject;
    }

    /**
     * Messages in inbox or message to be send.
     * 
     * @param messages
     * @return List of turned messages
     */
    public static List convertMails(Message[] messages) {
        List list = new ArrayList();
        for (int i = 0; i < messages.length; i++) {
            list.add(new Mail(messages[i]));
        }
        return list;
    }

    /**
     * Gives back the message's sender
     * 
     * @return sender
     */
    public String getFrom() {
        return from;
    }

    /**
     * Gives back the message's subject
     * 
     * @return Asunto del mensaje
     */
    public String getSubject() {
        return subject;
    }

    /**
     * Gives back the message's content
     * 
     * @return el texto del email
     */
    public String getMessageContent() {
        return messageContent;
    }

    /**
     * Delete a mail. set the message for its elimination.
     * 
     * @exception Exception
     *  
     */
    public void delete() throws Exception {
        message.setFlag(Flags.Flag.DELETED, true);
    }

    //SMTP METHODS

    /**
     * @param messageContent
     */
    public void setMessageContent(String messageContent) {
        this.messageContent = messageContent;
    }

    /**
     * @param name
     * @param address
     */
    public void addToAddress(String name, String address) {
        toAddresses.put(name, address);
    }

    /**
     * @param name
     * @param address
     */
    public void addCcAddress(String name, String address) {
        ccAddresses.put(name, address);
    }

    /**
     * @param name
     * @param address
     */
    public void addBccAddress(String name, String address) {
        bccAddresses.put(name, address);
    }

    /**
     * @param name
     * @param address
     */
    public void addReplyToAddress(String name, String address) {
        replyToAddresses.put(name, address);
    }

    /**
     * @return Devuelve bccAddresses.
     */
    public Hashtable getBccAddresses() {
        return bccAddresses;
    }

    /**
     * @return Devuelve ccAddresses.
     */
    public Hashtable getCcAddresses() {
        return ccAddresses;
    }

    /**
     * @return Devuelve message.
     */
    public MimeMessage getMessage() {
        return message;
    }

    /**
     * @return Devuelve replyToAddresses.
     */
    public Hashtable getReplyToAddresses() {
        return replyToAddresses;
    }

    /**
     * @return Devuelve toAddresses.
     */
    public Hashtable getToAddresses() {
        return toAddresses;
    }

    public MimeMessage parserMailToMimeMessage(MimeMessage sessionMimeMessage, Mail mail) throws Exception {
        MimeMessage mime = sessionMimeMessage;
        mime.setFrom(new InternetAddress(mail.getFrom()));
        mime.setSubject(mail.getSubject());
        mime.setSentDate(new java.util.Date());
        mime.setText(mail.getMessageContent());

        int naddrs = mail.getReplyToAddresses().size() + mail.getToAddresses().size() + mail.getCcAddresses().size() + mail.getBccAddresses().size();

        InternetAddress[] addresses = this.getAddresses(mail.getReplyToAddresses());
        if (addresses != null) {
            mime.setReplyTo(addresses);
            System.out.println(mime.getReplyTo().toString());
        }

        addresses = this.getAddresses(mail.getToAddresses());
        if (addresses != null) {
            mime.setRecipients(Message.RecipientType.TO, addresses);            
        }

        addresses = this.getAddresses(mail.getCcAddresses());
        if (addresses != null) {
            mime.setRecipients(Message.RecipientType.CC, addresses);
        }

        addresses = this.getAddresses(mail.getBccAddresses());
        if (addresses != null) {
            mime.setRecipients(Message.RecipientType.BCC, addresses);
        }
        
        System.out.println(mime.getSender());

        mime.saveChanges();
        return mime;
    }

    private InternetAddress[] getAddresses(Hashtable addresses) throws Exception {
        InternetAddress[] addrArray = null;
        String name = "";
        String addr = "";
        try {
            addrArray = new InternetAddress[addresses.size()];
            Enumeration keys = addresses.keys();
            for (int b = 0; b < addresses.size(); b++) {
                String key = (String) keys.nextElement();
                addr = (String) addresses.get(key);
                name = key;
                addrArray[b] = new InternetAddress((addr), name);
            }
        } catch (Exception e) {
            throw new Exception ("mail address "+addr+" is invalid.");
        }
        return addrArray;
    }
}
